<template>
    <div>
        <el-card>
            <el-row :gutter="12" style="margin-bottom: 5px;">
                <el-col :span="8">
                  <el-input
                      placeholder="请输入ID"
                      class="input-with-select"
                      v-model="queryInfo.productId" style="width: 120px;"
                      clearable
                      @clear="getProductList"
                  >
                  </el-input>
                    <el-input
                        placeholder="请输入商品名称"
                        class="input-with-select"
                        v-model="queryInfo.name" style="width: 320px;margin-left: 5px;"
                        clearable
                        @clear="getProductList"
                    >
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="queryInfo.categoryId" clearable filterable  placeholder="分类" @clear="getProductList">
                            <el-option
                                v-for="item in categoryList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                </el-col>
                <el-col :span="4" class="form-inline">
                    <el-select v-model="queryInfo.vendorId" clearable filterable  placeholder="供应商" @clear="getProductList">
                            <el-option
                                v-for="item in vendorList"
                                :key="item.id"
                                :label="item.vendorName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" @click="getProductList"
                        >搜索</el-button
                    >
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" @click="editProduct({})"
                        >添加商品</el-button
                    >
                </el-col>
            </el-row>
            <el-table :data="productList" border stripe>
                 <el-table-column label="logo" width="110">
                    <template v-if="scope.row.logo" slot-scope="scope">
                        <img style="width: 90px;height: 120px;vertical-align: middle;border:1px solid #FFB6C1;border-radius:6px"
                            :src="imgBaseUrl + scope.row.logo +'?iopcmd=thumbnail&type=4&width=90'"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="id" prop="id"></el-table-column>
                <el-table-column label="名称" prop="name" width="180"></el-table-column>
                <el-table-column label="价格" prop="price"></el-table-column>
                <el-table-column label="大分类" prop="categoryName"></el-table-column>
                <el-table-column label="小分类" prop="subCategoryName"></el-table-column>
                <el-table-column label="供应商" prop="vendorName"></el-table-column>
                <el-table-column label="已售出" prop="sold"></el-table-column>
                <el-table-column label="图片">
                     <template slot-scope="scope">
                       <el-link @click="queryPictureList(scope.row.id)" click="queryPictureList(scope.row.id)">设置(<span style="color:red">{{scope.row.pictureNum}}</span>)</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="SKU">
                     <template slot-scope="scope">
                       <el-link @click="querySkuList(scope.row.id)">设置(<span style="color:red">{{scope.row.skuNum}}</span>)</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="停售时间" prop="offSaleDate"></el-table-column>
                <el-table-column label="状态">
                    <!-- 自定义列模板，使用作用域插槽，通过scope.row获取当前行的数据 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" active-value="Y" inactive-value='N' @change="productStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="排序">
                    <!-- 自定义列模板，使用作用域插槽，通过scope.row获取当前行的数据 -->
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.sortNo" @change="productSortNo(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="编辑">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            @click="editProduct(scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
                <!-- 分页 -->
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </el-card>
        <el-dialog title="修改商品" :visible.sync="addProductVisible" width="66%">
            <el-form :model="addProductForm" ref="addProductRef" :rules="addProductRules" label-width="150px">
                <el-form-item label="商品名称" prop="name">
                    <el-input
                        v-model="addProductForm.name"
                        class="form_ipt"
                    ></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                    <el-form-item label="分类" prop="categoryId">
                        <el-select v-model="addProductForm.categoryId" clearable placeholder="请选择" @change="getSubCategoryList(addProductForm.categoryId)">
                            <el-option
                                v-for="item in categoryList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="14">
                      <el-form-item label="子类" prop="subCategoryId">
                          <el-select v-model="addProductForm.subCategoryId" clearable placeholder="请选择">
                              <el-option
                                  v-for="item in subCategoryList"
                                  :key="item.id"
                                  :label="item.name"
                                  :value="item.id">
                              </el-option>
                          </el-select>
                      </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                      <el-form-item label="供应商" prop="vendorId">
                          <el-select v-model="addProductForm.vendorId" filterable clearable placeholder="请选择">
                              <el-option
                                  v-for="item in vendorList"
                                  :key="item.id"
                                  :label="item.vendorName"
                                  :value="item.id">
                              </el-option>
                          </el-select>
                      </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                    <el-form-item label="配送范围模式" prop="deliveryProvinceMode">
                        <el-select v-model="addProductForm.deliveryProvinceMode" clearable placeholder="请选择" style="wdith:120px;">
                            <el-option
                                key="include"
                                label="包含"
                                value="include">
                            </el-option>
                            <el-option
                                key="exclude"
                                label="排除"
                                value="exclude">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="14">
                    <el-form-item label="配送范围" prop="selectedProvinceList">
                        <el-select v-model="selectedProvinceList" multiple clearable placeholder="请选择"
                        @change="mutiSelectProvince" style="width:100%">
                            <el-option
                                v-for="item in provinceList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                        <el-col :span="10">
                            <el-form-item label="上线时间" prop="onSaleTime">
                                <el-date-picker
                                    v-model="addProductForm.onSaleTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="下线时间" prop="offSaleTime">
                                <el-date-picker
                                    v-model="addProductForm.offSaleTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                </el-row>


                <el-form-item label="快递费用模板" prop="shippingTemplateId">
                        <el-select v-model="addProductForm.shippingTemplateId" clearable placeholder="请选择">
                            <el-option
                                v-for="item in shippingTemplateList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                <el-form-item label="logo" prop="logo">
                    <div class="form_row">
                        <img
                            v-for="(item, index) in uploadList"
                            :src="imgBaseUrl + item"
                            :key="index"
                            class="upload_img"
                            width="160"
                            alt=""
                        />
                        <el-upload
                            class="upload-demo"
                            :limit="10"
                            :action="actionPath"
                            :on-success="handleImgSuccess"
                            :on-remove="handleImgRemove"
                            :on-exceed="handleExceed"
                            :show-file-list="false"
                            list-type="picture-card"
                        >
                            <img
                                class="el-upload-list__item-thumbnail"
                                :src="addProductForm.logo"
                                alt=""
                            />
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品简介" prop="introduction">
                    <quill-editor
                        v-model="addProductForm.introduction"
                        :options="editorOption"
                        ref="myQuillEditor"
                    />
                    <el-upload
                        id="pic_uploader"
                        v-show="false"
                        :action="actionPath"
                        :on-success="uploadPicDone"
                        :file-list="fileList"
                        list-type="picture"
                    >
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addProductVisible = false">取 消</el-button>
                <el-button type="primary" @click="addProduct">确 定</el-button>
            </span>
        </el-dialog>
        <picture-list ref="pictureList"></picture-list>
        <sku-list ref="skuList"></sku-list>
    </div>
</template>

<script>
import Api from "@/api/Api.js";
import MallApi from "@/api/Mall.js";
import PictureList from "./Picture.vue"
import SkuList from "./Sku.vue"
export default {
  components: {
    PictureList,
    SkuList,
  },
    data() {
        return {
            flagList:[{'id':'jingxuan','name':'精选'},{'id':'fupin', 'name':'扶贫'}],
            flagCheckList:[],
            imgBaseUrl: this.$global.imgBaseUrl,
            actionPath: process.env.VUE_APP_BASE_API + "api/upload/image",
            vendorList: [],
            provinceList: [],
            categoryList: [],
            shippingTemplateList: [],
            subCategoryList:[],
            fileList: [],
            uploadList: [],
            addBannerVisible: false,
            selectedProvinceList: [],
            elecBatchList:[],
            selectedGoodsId:null,
            selectedGoodsPartnerCode:null,
            selectGoodsVisible:false,
            editorOption: {
                //符文本编辑器的配置
                placeholder: "",
                theme: "snow",
                modules: {
                    toolbar: {
                        container: [
                            // 工具栏配置, 默认是全部
                            ["bold"],
                            ["italic"],
                            ["underline"],
                            ["strike"],
                            [{ list: "ordered" }, { list: "bullet" }],
                            ["blockquote"],
                            ["code-block"],
                            ["link"],
                            ["image"],
                            [{ list: "ordered" }, { list: "bullet" }],
                        ],
                        handlers: {
                            image: function (value) {
                                if (value) {
                                    // 给个点击触发Element-ui，input框选择图片文件
                                    document
                                        .querySelector("#pic_uploader input")
                                        .click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
            queryInfo: {
                productId:'',
                name: "",
                pagenum: 1, // 页码
                pagesize: 10, // 页大小
            },
            productList: [],
            total: 0,
            addProductVisible: false,
            addProductForm: {
                id: "",
                logo: "",
                name: "",
                tingsType:"entity",
                introduction: "",
                deliveryProvincecodes: "",
                partnerGoodsId:'',
                partnerCode:'',
                parentGoodsName:'',
                relateProductIds:''
            },
            addProductRules: {
                logo: [
                    {
                        required: true,
                        message: "请输入封面地址",
                        trigger: "change",
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "change",
                    }
                ],
                categoryId: [
                    {
                        required: true,
                        message: "请选择分类",
                        trigger: "change",
                    }
                ],
                subCategoryId: [
                    {
                        required: true,
                        message: "请选择分类子类",
                        trigger: "change",
                    }
                ],
                vendorId: [
                    {
                        required: true,
                        message: "请选择供应商",
                        trigger: "change",
                    }
                ],
                shipperId: [
                    {
                        required: true,
                        message: "请选择发货商",
                        trigger: "change",
                    }
                ],
                shippingTemplateId: [
                    {
                        required: true,
                        message: "请选择快递费用模板",
                        trigger: "change",
                    }
                ],
                onSaleTime: [
                    {
                        required: true,
                        message: "请选择上线时间",
                        trigger: "blur",
                    },
                ],
                offSaleTime: [
                    {
                        required: true,
                        message: "请选择下线时间",
                        trigger: "blur",
                    },
                ],
                introduction: [
                    {
                        required: true,
                        message: "请输入商品简介",
                        trigger: "change",
                    }
                ],
            }
        };
    },
    watch: {
        addProductForm: {
            handler(val, oldVal) {
                if (val.onSaleTime) {
                    this.addProductForm.onSaleTime = this.formatTime(
                        val.onSaleTime,
                        "yyyy-MM-dd HH:mm:ss"
                    );
                }
                if (val.offSaleTime) {
                    this.addProductForm.offSaleTime = this.formatTime(
                        val.offSaleTime,
                        "yyyy-MM-dd HH:mm:ss"
                    );
                }
            },
            deep: true,
        }
    },
    created() {
        this.getProductList();
        this.getVendorList();
        this.getCategoryList();
    },
    methods: {
        getProductList() {
          MallApi.getProductList(this.queryInfo).then((res) => {
                if (res.success) {
                    this.productList = res.data.productList;
                    this.total = res.data.page.total;
                } else {
                    return this.$message.error("获取商品列表失败");
                }
            });
        },
        getSubCategoryList(categoryId) {
          MallApi.getSubCategoryList({'categoryId':categoryId}).then((res) => {
                if (res.success) {
                    this.subCategoryList = res.data.subCategoryList;
                } else {
                    return this.$message.error("获取商品列表失败");
                }
            });
        },
        getVendorList() {
          MallApi.getVendorList({"isAll":"Y"}).then((res) => {
                if (res.success) {
                    this.vendorList = res.data.vendorList;
                } else {
                    return this.$message.error("获取供应商列表失败");
                }
            });
        },
         getCategoryList() {
           MallApi.getCategoryList({'pagesize':100}).then((res) => {
                if (res.success) {
                    this.categoryList = res.data.categoryList;
                    this.total = res.data.page.total;
                } else {
                    return this.$message.error("获取分类列表失败");
                }
            });
        },
        handleSizeChange(pagesize) {
            this.queryInfo.pagenum = 1;
            this.queryInfo.pagesize = pagesize;
            this.getProductList();
        },
        // 监听pagenum的事件
        handleCurrentChange(pagenum) {
            this.queryInfo.pagenum = pagenum;
            this.getProductList();
        },
        newProduct() {
            this.addProductVisible = true;
            this.flagCheckList = []
            this.addProductForm = {
                id: "",
                logo: "",
                name: "",
                introduction: "",
                flag:''
            };
        },
        editProduct(info) {
             let uploadList = [];
            uploadList.push(info.logo);
            this.uploadList = uploadList;
          MallApi.getProductDetail({
                id: info.id,
            }).then((res) => {
                if (res.success) {
                    this.addProductVisible = true;
                    this.addProductForm = JSON.parse(JSON.stringify(res.data.product));
                    if(this.addProductForm.flag && this.addProductForm.flag != ''){
                        this.flagCheckList = this.addProductForm.flag.split(',');
                    }else {
                        this.flagCheckList = []
                    }
                    this.categoryList = res.data.categoryList;
                    this.vendorList = res.data.vendorList;
                    this.shippingTemplateList = res.data.shippingTemplateList;
                    this.provinceList = res.data.provinceList;
                    this.addProductForm.parentGoodsName = res.data.parentGoodsName;
                    if(res.data.product.deliveryProvincecodes){
                        var selectPro=[];
                        var codesspt = res.data.product.deliveryProvincecodes.split(',');
                        for (var cs in codesspt){
                            selectPro.push(parseInt(codesspt[cs]));
                        }
                        this.selectedProvinceList = selectPro;
                    }else {
                        this.selectedProvinceList = []
                    }
                    if(this.addProductForm.categoryId){
                        this.getSubCategoryList(this.addProductForm.categoryId);
                    }
                }
            });
        },
        uploadPicDone(response, file, logoList) {
            console.log(response, file, logoList);
            let quill = this.$refs.myQuillEditor.quill;
            if (response.success) {
                let length = quill.getSelection().index;
                // 插入图片 response.data.url为服务器返回的图片地址
                quill.insertEmbed(
                    length,
                    "image",
                    this.imgBaseUrl + response.data
                );
                // 调整光标到最后
                quill.setSelection(length + 1);
            } else {
                this.$message.error("图片插入失败");
            }
            this.logoList = logoList;
            // this.uillUpdateImg = false;
        },
        switchHotStatus(){},
        // 添加电影
        addProduct() {
            this.$refs.addProductRef.validate((valid) => {
                if (valid) {
                    this.addProductForm.flag= this.flagCheckList.join(',');
                  MallApi.saveProduct(this.addProductForm).then((res) => {
                        if (res.success) {
                            this.addProductVisible = false;
                            this.getProductList();
                        }else {
                          return this.$message.error("保存失败：" + res.msg);
                        }
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        productStateChange(product) {
          MallApi.setProductStatus({'id':product.id, 'status':product.status}).then(res => {
                if (res.success) {
                    this.$message.success('更新状态成功！')
                } else {
                    product.status = (product.status=='Y'?'N':'Y')
                    return this.$message.error('更新状态失败：' + res.msg)
                }
            })
        },
        productSortNo(product) {
          MallApi.setProductSortNo({'id':product.id, 'sortNo':product.sortNo}).then(res => {
                if (res.success) {
                    this.$message.success('更新排序成功！')
                } else {
                    return this.$message.error('更新排序失败：' + res.msg)
                }
            })
        },
        handleImgSuccess(res, file, logoList) {
            this.addProductForm.logo = res.data;
            let uploadList = [];
            uploadList.push(res.data);
            this.uploadList = uploadList;
        },
        handleImgRemove(res, file) {
            console.log(res, file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件`);
        },
        queryPictureList(productId) {
            this.$refs.pictureList.showPictureList(productId);
        },
        querySkuList(productId) {
            this.$refs.skuList.showSkuList(productId);
        },
        mutiSelectProvince(val){
            console.info(val);
            if(val){
                this.addProductForm.deliveryProvincecodes = val.join(',');
                console.info(this.editProduct.deliveryProvincecodes);
            }else {
                 this.addProductForm.deliveryProvincecodes = '';
            }
        },
        selectBlueGoods(){
          this.selectedGoodsPartnerCode = this.addProductForm.partnerCode;
          this.selectedGoodsId = this.addProductForm.partnerGoodsId+"";
          this.selectGoodsVisible = true;
        },
        closeSelectGoodsDialog(data){
          this.selectGoodsVisible = false;
          this.selectedGoodsId = null;
          this.selectedGoodsPartnerCode = null;
        },

        getGoods(row){
          this.addProductForm.partnerGoodsId = row.productId;
          this.addProductForm.partnerCode = row.channel;
          this.addProductForm.parentGoodsName = row.itemName;
        },
    }
};
</script>

<style>
.form_ipt {
    width: 450px;
}
</style>
